import permissionApi from "@/js_sdk/wa-permission/permission"
import Storage from "@/libs/Storage";
import moment from "@/vendor/day";
import utils from "@/libs/utils";

export default {
  async check(permission) {
    const res = await Storage.get('permission_' + permission)
    console.log('checkPermission', res)
    return res
  },
  async request(permission, params = null) {
    // #ifndef APP-PLUS
    await Storage.set('permission_' + permission, 1)
    return {status: 1, msg: '已获得授权'}
    // #endif

    // #ifdef APP-PLUS
    let val

    if (permission === 'location') {
      val = 'android.permission.ACCESS_FINE_LOCATION'
    } else if (permission === 'camera') {
      val = 'android.permission.CAMERA'
    } else if (permission === 'album') {
      val = 'android.permission.READ_EXTERNAL_STORAGE'
    }

    let alert
    if (params) {
      alert = utils.showAlert(params.title, params.desc)
    }

    const result = await permissionApi.requestAndroidPermission(val)

    let strStatus
    if (result === 1) {
      strStatus = "已获得授权"
      await Storage.set('permission_' + permission, 1)
    } else if (result === 0) {
      strStatus = "未获得授权"
      await Storage.del('permission_' + permission)
    } else {
      await Storage.set('permission_' + permission, -1)
      strStatus = "被永久拒绝权限"
    }
    console.log('requestAndroidPermission', strStatus, result)

    if(alert) {
      alert.dismiss()
    }

    return {status: result, msg: strStatus}
    // #endif
  },
  async skipToday(permission) {
    const today = moment().format('YYYY-MM-DD')
    await Storage.set('skip_permission_' + permission + '_' + today, 1)
  },
  async isRequestedToday(permission) {
    const today = moment().format('YYYY-MM-DD')
    return await Storage.get('skip_permission_' + permission + '_' + today, 0)
  }
}
